#include <header.h>
int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 1);

	char *port = "8080";
	char *ip = "192.168.169.128";
	int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
	ERROR_CHECK(socket_fd, -1, "socket");

	// 端口复用
	int reuse = 1;
	setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof reuse);


	struct sockaddr_in serveraddr;
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi(port));
	serveraddr.sin_addr.s_addr = inet_addr(ip);
	int ret_bind = bind(socket_fd, (struct sockaddr*)&serveraddr, sizeof serveraddr);
	ERROR_CHECK(ret_bind, -1, "bind");
	
	int ret_listen = listen(socket_fd, 10);
	ERROR_CHECK(ret_listen, -1, "listen");


	struct sockaddr_in user1;
	socklen_t len = sizeof(user1);
	// 阻塞函数
	int net_fd = accept(socket_fd, (struct sockaddr*)&user1, &len);
	ERROR_CHECK(net_fd, -1, "accept");
	// printf("port %d\n", htons(user1.sin_port));
	// printf("ip:%s\n", inet_ntoa(user1.sin_addr));

	fd_set set, set_bak;
	FD_ZERO(&set);
	FD_ZERO(&set_bak);
	FD_SET(STDIN_FILENO, &set_bak);
	FD_SET(net_fd, &set_bak);
	
	while(1){
		memcpy(&set, &set_bak, sizeof set_bak);

		int res = select(10, &set, NULL, NULL, NULL);
		ERROR_CHECK(res, -1, "select");
		
		if(FD_ISSET(socket_fd, &set)){
			// 客户端重新连接
			net_fd = accept(socket_fd, NULL, NULL);
			FD_CLR(socket_fd, &set_bak);
			FD_SET(STDIN_FILENO, &set_bak);
			FD_SET(net_fd, &set_bak);			
		}


		char buf[1 << 10] = {0};
		if(FD_ISSET(STDIN_FILENO, &set)){
			__bzero(buf, sizeof buf);
			read(STDIN_FILENO, buf, sizeof buf);
			send(net_fd, buf, sizeof buf, 0);
		}

		if(FD_ISSET(net_fd, &set)){
			__bzero(buf, sizeof buf);
			ssize_t byte = recv(net_fd, buf, sizeof buf, 0);
			ERROR_CHECK(byte, -1, "recv");
			if(byte == 0){
				FD_CLR(net_fd, &set_bak);
				FD_CLR(STDIN_FILENO, &set_bak);

				FD_SET(socket_fd, &set_bak);
				continue;
			}
			printf("client:%s\n", buf);		
		}
	}
	close(net_fd);
	close(socket_fd);
	return 0;
}